package controllers

import (
	"github.com/gin-gonic/gin"
	"shoping.zozoo.net/model"
	"shoping.zozoo.net/params"
	"shoping.zozoo.net/service"
	"shoping.zozoo.net/tool"
	"strconv"
)

type OrderController struct {
	service service.OrderInterface
}

func NewOrderController(s service.OrderInterface) *OrderController {
	return &OrderController{
		s,
	}
}

//获取订单列表
func (o *OrderController) List(c *gin.Context) {
	var (
		list []*model.Order
		err  error
	)

	if list, err = o.service.GetOrderAll(); err != nil {
		tool.ResponseError(c, tool.Fail, err.Error())
		return
	}

	tool.ResponseSuccess(c, list)
}

//创建订单
func (o *OrderController) Insert(c *gin.Context) {
	var (
		id    int64
		err   error
		param *params.OrderParam
	)

	//参数验证
	param = &params.OrderParam{}
	if err = c.ShouldBindJSON(param); err != nil {
		tool.ResponseError(c, tool.BadRequest, err.Error())
		return
	}

	//获取插入结果
	if id, err = o.service.InsertOrder(param); err != nil {
		tool.ResponseError(c, tool.Fail, err.Error())
		return
	}

	tool.ResponseSuccess(c, id)
}

//删除订单
func (o *OrderController) Delete(c *gin.Context) {
	var (
		id  int64
		err error
		ok  bool
	)
	if id, err = strconv.ParseInt(c.Param("id"), 10, 64); err != nil {
		tool.ResponseError(c, tool.Fail, "参数错误")
		return
	}

	if ok, err = o.service.DelOrderById(id); err != nil {
		tool.ResponseError(c, tool.Fail, err.Error())
		return
	}

	if !ok {
		tool.ResponseError(c, tool.Fail, "删除失败")
		return
	}

	tool.ResponseSuccess(c, ok)
}

//获取订单详情
func (o *OrderController) Get(c *gin.Context){
	var (
		id  int64
		err error
		order *model.Order
	)
	if id, err = strconv.ParseInt(c.Param("id"), 10, 64); err != nil {
		tool.ResponseError(c, tool.Fail, "参数错误")
		return
	}

	if order,err = o.service.GetOrderById(id);err != nil {
		tool.ResponseError(c, tool.Fail, err.Error())
		return
	}

	tool.ResponseSuccess(c,order)
}
